# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
import calendar
import time
import tkFont
import thread

from Persistance import *
from iSchedule import Event
from iCalendar import CalendarGUI
from iStay import StayGUI
from iCleaning import CleaningGUI
## from iTechnical import TechnicalGUI
## from iOcupancy import OcupancyGUI
## from iBill import BillGUI

class CleaningScheduleGUI(Frame):
	def __init__(self, balloon=None, mainFrame=None, path=None, log=None):
		Frame.__init__(self)
		self.balloon=balloon
		self.mainFrame=mainFrame
		self.daysFT = tkFont.Font(family="Helvetica", size=6, weight="normal")
		self.numberFT = tkFont.Font(family="Helvetica", size=10, weight="bold")
		self.monthFT = tkFont.Font(family="Helvetica", size=12, weight="bold")
		self.imgCalendar=PhotoImage(file="img/calendar.gif")
		self.daysList = Glob.DAYS_LIST
		self.monthList= Glob.MONTH_LIST
		self.path=path
		self.log=log
		self.log.info("\tCleaningScheduleGUI\tStart")
		self.reservation()

	# DEBUT Planning des ménages ****************************************************************************
	def reservation(self):
		self.reservationFrame = Frame(self.mainFrame)
		# Choix de la résidence pour afficher son planning de reservation
		choiceFrame=Frame(self.reservationFrame)
		# Menu deroulant permettant de choisir le mode d'afffichage années ou semaines
		self.screenModeCB=Pmw.ComboBox(	choiceFrame, 
																		labelpos = u"w", 
																		label_text = u"Affichage : ", 
																		selectioncommand=self.selectScreenMode,
																		entry_width = 8,
																		listheight=60 )
		self.screenModeCB.pack(side=LEFT)
		self.fillScreenMode()
		self.screenModeCB.selectitem(0)
		self.cal1Value=StringVar()
		self.myCal1=Button(choiceFrame, image=self.imgCalendar, command=lambda x=self.cal1Value:self.ctrlCalendar(x), padx=4, pady=1)
		self.myCal1.pack(side=LEFT)
		self.balloon.bind(self.myCal1, u"Calendrier")
		self.myCal1.config(state=DISABLED)
		self.monthCB=Pmw.ComboBox(	choiceFrame, 
																labelpos = u"w", 
																label_text = u"Mois : ", 
																selectioncommand=self.selectMonth, 
																entry_width = 9,
																listheight=220 )
		self.monthCB.pack(side=LEFT)
		self.fillMonthCB()
		self.monthCB.selectitem(int(time.strftime('%m', time.localtime())) - 1)
		self.month_selected=int(time.strftime('%m', time.localtime())) - 1
		self.monthCB.component('entryfield_entry').configure(state=DISABLED)
		self.monthCB.component('scrolledlist_listbox').configure(state=DISABLED)
		# Create the Counters for de Year.
		self.reservationYearC=Pmw.Counter(	choiceFrame,
												labelpos = u"w",
												label_text = u"Année : ",
												entryfield_value =int(time.strftime('%Y', time.localtime())),
												entry_width = 4,
												entryfield_validate = {"validator" : "integer", "min" : 2000})
		self.reservationYearC.pack(side=LEFT)
		self.reservationPlaceCB=Pmw.ComboBox(	choiceFrame, 
																				labelpos = u"w", 
																				label_text = u"Résidence : ", 
																				selectioncommand=self.selectReservationPlace,
																				entry_width = 19,
																				listheight=120)
		self.reservationPlaceCB.pack(side=LEFT)
		self.fillReservationPlace()
		self.reservationPlaceCB.selectitem(0)
		Label(choiceFrame, width=16, text="Semaine : "+time.strftime('%W', time.localtime())+" - Date :", anchor=E).pack(side=LEFT)
		self.dateE=Entry(choiceFrame, width=9, textvariable=self.cal1Value, state=NORMAL)
		self.dateE.pack(side=LEFT)
		self.cal1Value.set(time.strftime("%d/%m/%Y" ,time.localtime()))
		self.dateE.config(state=DISABLED)
		choiceFrame.pack(side=TOP, fill=X)
		# Canvas
		self.reservationSC=Pmw.ScrolledCanvas(self.reservationFrame,
															usehullsize=1,
															hull_width=800,
															hull_height=400,
															canvas_bg="white", canvasmargin=5,
															borderframe=1,
															borderframe_borderwidth=1)
		# Les options ci-dessous doivent être précisées après initialisation :
		self.reservationSC.configure(vscrollmode="dynamic", hscrollmode="dynamic")
		self.reservationSC.pack(padx=5, pady=5, expand=YES, fill=BOTH)
		self.reservationFrame.pack(side=TOP, fill=BOTH, expand=YES)

	def close(self):
		self.reservationFrame.destroy()

	def drawReservationByYear(self):
		# Effacer le canvas
		listObject=self.reservationSC.find_all()
		for id in listObject:
			self.reservationSC.delete(id)
		# Reinitialiser la position de la scrolbar X	
		self.movetoXView()
		# Dessiner les lignes horizontal en fonction du nombre de produit (Product)
		year=int(self.reservationYearC.get())
		# Année bissextil ?
		ab=calendar.monthrange(year, 02)
		feb=ab[1]
		if feb==29: daysOfYear=366
		else: daysOfYear=365
		x_length=60*daysOfYear
		y_space=60
		y=60
		self.reservationSC.create_line(0, y, x_length, y)
		y+=y_space
		for product in self.reservationProductListFromPlace:
			tg="obj"+str(product.id)
			self.reservationSC.create_line(0, y, x_length, y, fill="grey60")
			y+=y_space
		# Dessiner le calendrier pour l'année séléctionnée
		y_length=y-60
		x=60
		x_space=60
		# countWK=1
		for mth in range(1,13):
			self.reservationSC.create_text(x-55, 0,  text=self.monthList[mth-1], fill="blue", font=self.monthFT, anchor=NW)
			if mth!=1:self.reservationSC.create_line(x-60, 0, x-60, 40, fill="red", dash=(2, 2))
			month=calendar.monthcalendar(year, mth)
			for week in month:
				# self.reservationSC.create_text(x+57, 20,  text="Semaine  "+str(countWK), fill="blue", font=self.numberFT, anchor=NW)
				countDay=0
				for date in week:
					if date!=0:
						if countDay==5:self.reservationSC.create_line(x, 20, x, y_length, fill="red")
						else:self.reservationSC.create_line(x, 40, x, y_length, fill="red", dash=(2, 2))
						self.reservationSC.create_text(x-3, 40,  text=str(date), fill="blue", font=self.numberFT, anchor=NE)
						self.reservationSC.create_text(x-57, 40,  text=self.daysList[countDay], fill="blue", font=self.daysFT, anchor=NW)
						x+=x_space
					countDay+=1
				# countWK+=1
		# Si affichage de l'année en cours dessiner le curseur a la date du jour
		if time.strftime("%Y" ,time.localtime()) == self.reservationYearC.get():
			today=time.strftime("%j" ,time.localtime())
			x=int(today)*60
			self.reservationSC.create_line(x, 20, x, y_length, fill="green", width=4)
			self.reservationSC.create_line(x-60, 20, x-60, y_length, fill="green", width=4)
			self.reservationSC.create_line(x-60, 20, x, 20, fill="green", width=4)
			self.reservationSC.create_line(x-60, y_length, x, y_length, fill="green", width=4)
		# posPix=x-60
		# Dessiner les évenements du planning (produit reserver en option, sale, en intervention technique)
		self.eventList=[]
		y_pos=65
		line=10000
		oddAndEven=100000
		eventNum=0
		monthList=(31,feb,31,30,31,30,31,31,30,31,30,31)
		monthListDate=("01","02","03","04","05","06","07","08","09","10","11","12")
		for product in self.reservationProductListFromPlace:
			count=0
			x_pos=5
			day=0
			dayOut=31
			indexMonthList=1
			month="01"
			while count<daysOfYear:
				if day<dayOut:
					day+=1
				else:
					day=1
					dayOut=monthList[indexMonthList]
					month=monthListDate[indexMonthList]
					indexMonthList+=1
				# Evenement demi journér AM
				e=Event()
				e.date=str(day)+"/"+month+"/"+str(year)
				e.hour=u"Matin"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+line+count))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position,e.y_position,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position, e.y_position,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				# Numero de la chambre
				e.objectTextID=self.reservationSC.create_text(e.x_position,e.y_position,text=product.number,fill="black",font=self.daysFT,anchor=NW)
				# Information sur le produit Infos Bulle
				balloonText=u"Famille de produit : "+product.productFamily.designation
				balloonText+=u"\nRéférence : "+product.reference.code
				balloonText+=u"\nDésignation : "+product.designation
				if product.description!=None and product.description!= "":balloonText+=u"\n---------------  Description \n"+product.description+u"\n---------------"
				if product.number!="0":balloonText+=u"\nNuméro : "+product.number
				balloonText+=u"\nNombre de couchage : "+str(product.sleeps)
				if product.area!=0:balloonText+=u"\nSurface : "+str(product.area)+u"m²"
				if product.floor!=0:balloonText+=u"\nEtage : "+str(product.floor)
				if product.tel!=None and product.tel!= "":balloonText+=u"\nTéléphone : "+product.tel
				if product.status=="S":balloonText+=u"\nEtat : Sale"
				elif product.status=="A":balloonText+=u"\nEtat : A vérifier"
				elif product.status=="P":balloonText+=u"\nEtat : Propre"
				elif product.status=="I":balloonText+=u"\nEtat : Intervention"
				elif product.status=="T":balloonText+=u"\nEtat : Traveaux"
				elif product.status=="M":balloonText+=u"\nEtat : Maintennance"
				else: balloonText+=u"\nEtat : Fermé"
				self.balloon.tagbind(self.reservationSC, e.objectTextID, balloonText)

				self.eventList.append(e)
				# Evenement demi journér PM
				e=Event()
				e.date=str(day)+"/"+month+"/"+str(year)
				e.hour=u"Après-midi"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+oddAndEven+line+count))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position+e.size,e.y_position+e.size,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position+e.size, e.y_position+e.size,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				self.eventList.append(e) 
				x_pos+=60
				count+=1
				eventNum+=1
			y_pos+=60
			line+=10000
		self.reservationSC.resizescrollregion()
		# Positionner la scrollBar horizontal sur la date du jour si année en cours
		if int(today) > 0:
			self.movetoXView((1.0/daysOfYear)*int(today))

	def drawReservationByMonth(self):
		# Effacer le contenu du canvas
		listObject=self.reservationSC.find_all()
		for id in listObject:
			self.reservationSC.delete(id)
		# Reinitialiser la position de la scrolbar X	
		self.movetoXView()
		# Dessiner les lignes horizontal en fonction du nombre de produit (Product)
		# Recuperer l"année selectionnée
		year=int(self.reservationYearC.get())
		# Nombre de jour dans le mois a afficher
		ab=calendar.monthrange(year, self.month_selected+1)
		# Nombre de jour afficher (1 mois par defaut)
		days4Weeks=ab[1]
		x_length=60*days4Weeks
		y_space=60
		y=60
		# Dessiner la ligne horizontal d'entete
		self.reservationSC.create_line(0, y, x_length, y)
		y+=y_space
		# Dessiner une ligne horizntal pour chaque produit
		for product in self.reservationProductListFromPlace:
			tg="obj"+str(product.id)
			self.reservationSC.create_line(0, y, x_length, y, fill="grey60")
			y+=y_space
		# Dessiner le calendrier pour les 3 semaines séléctionnée
		y_length=y-60
		x=60
		x_space=60
		# DESSIN DU CALENDRIER POUR LE MOIS
		# Le nom du mois	
		self.reservationSC.create_text(x-55, 0,  text=self.monthList[self.month_selected], fill="blue", font=self.monthFT, anchor=NW)
		month=calendar.monthcalendar(year, self.month_selected +1)
		for  week in month:
			countDay=0
			for date in week:
				if date!=0:
					if countDay==5:self.reservationSC.create_line(x, 20, x, y_length, fill="red")
					else:self.reservationSC.create_line(x, 40, x, y_length, fill="red", dash=(2, 2))
					self.reservationSC.create_text(x-3, 40,  text=str(date), fill="blue", font=self.numberFT, anchor=NE)
					self.reservationSC.create_text(x-57, 40,  text=self.daysList[countDay], fill="blue", font=self.daysFT, anchor=NW)
					x+=x_space
				countDay+=1
				
		# Si affichage du mois en cours dessiner le curseur a la date du jour
		today=0
		if ( time.strftime("%Y" ,time.localtime()) == self.reservationYearC.get() ) and ( int(time.strftime("%m" ,time.localtime())) == self.month_selected+1 ):
			today=time.strftime("%d" ,time.localtime())
			x=int(today)*60
			self.reservationSC.create_line(x, 20, x, y_length, fill="green", width=4)
			self.reservationSC.create_line(x-60, 20, x-60, y_length, fill="green", width=4)
			self.reservationSC.create_line(x-60, 20, x, 20, fill="green", width=4)
			self.reservationSC.create_line(x-60, y_length, x, y_length, fill="green", width=4)
		
		# Dessiner les évenements du planning (produit reserver en option, sale, en intervention technique)
		self.eventList=[]
		y_pos=65
		line=10000
		oddAndEven=100000
		eventNum=0
		for product in self.reservationProductListFromPlace:
			x_pos=5
			day=0
			dayOut=days4Weeks
			month=str(self.month_selected+1)
			while day<dayOut:
				day+=1
				# Evenement demi journér AM
				e=Event()
				e.date=str(day)+"/"+month+"/"+str(year)
				e.hour=u"Matin"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+line+day-1))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position,e.y_position,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position, e.y_position,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				# Numero de la chambre
				e.objectTextID=self.reservationSC.create_text(e.x_position,e.y_position,text=product.number,fill="black",font=self.daysFT,anchor=NW)
				# Information sur le produit Infos Bulle
				balloonText=u"Famille de produit : "+product.productFamily.designation
				balloonText+=u"\nRéférence : "+product.reference.code
				balloonText+=u"\nDésignation : "+product.designation
				if product.description!=None and product.description!= "":balloonText+=u"\n---------------  Description \n"+product.description+u"\n---------------"
				if product.number!="0":balloonText+=u"\nNuméro : "+product.number
				balloonText+=u"\nNombre de couchage : "+str(product.sleeps)
				if product.area!=0:balloonText+=u"\nSurface : "+str(product.area)+u"m²"
				if product.floor!=0:balloonText+=u"\nEtage : "+str(product.floor)
				if product.tel!=None and product.tel!= "":balloonText+=u"\nTéléphone : "+product.tel
				if product.status=="S":balloonText+=u"\nEtat : Sale"
				elif product.status=="A":balloonText+=u"\nEtat : A vérifier"
				elif product.status=="P":balloonText+=u"\nEtat : Propre"
				elif product.status=="I":balloonText+=u"\nEtat : Intervention"
				elif product.status=="T":balloonText+=u"\nEtat : Traveaux"
				elif product.status=="M":balloonText+=u"\nEtat : Maintennance"
				else: balloonText+=u"\nEtat : Fermé"
				self.balloon.tagbind(self.reservationSC, e.objectTextID, balloonText)

				self.eventList.append(e)
				# Evenement demi journér PM
				e=Event()
				e.date=str(day)+"/"+month+"/"+str(year)
				e.hour=u"Après-midi"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+oddAndEven+line+day-1))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position+e.size,e.y_position+e.size,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position+e.size, e.y_position+e.size,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				self.eventList.append(e) 
				x_pos+=60
				eventNum+=1
			y_pos+=60
			line+=10000
		self.reservationSC.resizescrollregion()
		# Positionner la scrollBar horizontal sur la date du jour si mois en cours
		if int(today) > 0:
			self.movetoXView((1.0/days4Weeks)*int(today))

	def drawReservationByDay(self):
		# Effacer le contenu du canvas
		listObject=self.reservationSC.find_all()
		for id in listObject:
			self.reservationSC.delete(id)
		# Reinitialiser la position de la scrolbar X	
		self.movetoXView()
		# Dessiner les lignes horizontal en fonction du nombre de produit (Product)
		# Recuperer la date selectionnée
		date_selected=self.cal1Value.get()
		dl=date_selected.split('/')
		year=int(dl[2])
		month=int(dl[1])
		day=int(dl[0])
		# Nombre de jour dans le mois 
		ab=calendar.monthrange(year, month)
		# Nombre de jour afficher (10 par defaut)
		daysMonth=ab[1]
		# Verifier si affichage d'une période a cheval sur 2 mois
		if day == 1:
			if month == 1:
				first_month=12
				first_year=year-1
			else:
				first_month= month-1
				first_year=year
			ab=calendar.monthrange(first_year, first_month)
			first_daysMonth=ab[1]
			first_day=first_daysMonth-1
			listTenDay=[int(first_daysMonth-1), int(first_daysMonth), 1, 2, 3, 4, 5, 6, 7,8]
			last_day=day+7
			last_month=month
			last_year=year
		if day == 2:
			if month == 1:
				first_month=12
				first_year=year-1
			else:
				first_month=month-1
				first_year=year
			ab=calendar.monthrange(first_year, first_month)
			first_daysMonth=ab[1]
			first_day=first_daysMonth
			listTenDay=[int(first_daysMonth), 1, 2, 3, 4, 5, 6, 7,8,9]
			last_day=day+7
			last_month=month
			last_year=year
		if day > 2:
			first_day=day-2
			listTenDay=[int(day-2), int(day-1), int(day)]
			first_month=month
			first_year=year
			if (day + 7) > daysMonth:
				last_day=(day+7)-daysMonth
				t=day
				u=1
				for v in range(1,8):
					t+=1
					if t>daysMonth:
						listTenDay.append(int(u))
						u+=1
					else:
						listTenDay.append(int(t))
				if month == 12:
					last_month=1
					last_year=year+1
				else:
					last_month=month+1
					last_year=year
			else:
				last_day=day+7
				listTenDay.append(int(day+1))
				listTenDay.append(int(day+2))
				listTenDay.append(int(day+3))
				listTenDay.append(int(day+4))
				listTenDay.append(int(day+5))
				listTenDay.append(int(day+6))
				listTenDay.append(int(day+7))
				last_month=month
				last_year=year
		
		## self.log.info("\t\tlistTenDay")
		## p=0
		## for a in listTenDay:
			## self.log.info("\tposition : "+str(p)+"\tvalue : "+str(a))
			## p+=1
		## self.log.info("\t\tValeurs des dates")
		## self.log.info("\t Date selectionner\t"+str(day)+"/"+str(month)+"/"+str(year))
		## self.log.info("\t first date\t"+str(first_day)+"/"+str(first_month)+"/"+str(first_year))
		## self.log.info("\t last date\t"+str(last_day)+"/"+str(last_month)+"/"+str(last_year))
		
		x_length=60*10
		y_space=60
		y=60
		# Dessiner la ligne horizontal d'entete
		self.reservationSC.create_line(0, y, x_length, y)
		y+=y_space
		# Dessiner une ligne horizntal pour chaque produit
		for product in self.reservationProductListFromPlace:
			tg="obj"+str(product.id)
			self.reservationSC.create_line(0, y, x_length, y, fill="grey60")
			y+=y_space
		# Dessiner le calendrier pour les 3 semaines séléctionnée
		y_length=y-60
		x=60
		x_space=60
		
		# DESSIN DU CALENDRIER POUR LA PERIODE DE 10 JOURS
		if first_month == last_month:
			self.reservationSC.create_text(x-55, 0,  text=self.monthList[first_month-1], fill="blue", font=self.monthFT, anchor=NW)
			mcal=calendar.monthcalendar(first_year, first_month)
			for  week in mcal:
				countDay=0
				for date in week:
					if date!=0 and date >= first_day and date <= last_day:
						if countDay==5:self.reservationSC.create_line(x, 20, x, y_length, fill="red")
						else:self.reservationSC.create_line(x, 40, x, y_length, fill="red", dash=(2, 2))
						self.reservationSC.create_text(x-3, 40,  text=str(date), fill="blue", font=self.numberFT, anchor=NE)
						self.reservationSC.create_text(x-57, 40,  text=self.daysList[countDay], fill="blue", font=self.daysFT, anchor=NW)
						x+=x_space
					countDay+=1
		else:
			self.reservationSC.create_text(x-55, 0,  text=self.monthList[first_month-1], fill="blue", font=self.monthFT, anchor=NW)
			mcal=calendar.monthcalendar(first_year, first_month)
			for  week in mcal:
				countDay=0
				for date in week:
					if date!=0 and date >= first_day:
						if countDay==5:self.reservationSC.create_line(x, 20, x, y_length, fill="red")
						else:self.reservationSC.create_line(x, 40, x, y_length, fill="red", dash=(2, 2))
						self.reservationSC.create_text(x-3, 40,  text=str(date), fill="blue", font=self.numberFT, anchor=NE)
						self.reservationSC.create_text(x-57, 40,  text=self.daysList[countDay], fill="blue", font=self.daysFT, anchor=NW)
						x+=x_space
					countDay+=1
			self.reservationSC.create_text(x-55, 0,  text=self.monthList[last_month-1], fill="blue", font=self.monthFT, anchor=NW)
			mcal=calendar.monthcalendar(last_year, last_month)
			for  week in mcal:
				countDay=0
				for date in week:
					if date!=0 and date <= last_day:
						if countDay==5:self.reservationSC.create_line(x, 20, x, y_length, fill="red")
						else:self.reservationSC.create_line(x, 40, x, y_length, fill="red", dash=(2, 2))
						self.reservationSC.create_text(x-3, 40,  text=str(date), fill="blue", font=self.numberFT, anchor=NE)
						self.reservationSC.create_text(x-57, 40,  text=self.daysList[countDay], fill="blue", font=self.daysFT, anchor=NW)
						x+=x_space
					countDay+=1		
					
		# Affichage du jour séléctionner dessiner le curseur
		x=3*60
		self.reservationSC.create_line(x, 20, x, y_length, fill="blue", width=4)
		self.reservationSC.create_line(x-60, 20, x-60, y_length, fill="blue", width=4)
		self.reservationSC.create_line(x-60, 20, x, 20, fill="blue", width=4)
		self.reservationSC.create_line(x-60, y_length, x, y_length, fill="blue", width=4)
		
		# Dessiner les évenements du planning (produit reserver en option, sale, en intervention technique)
		self.eventList=[]
		y_pos=65
		line=10000
		oddAndEven=100000
		eventNum=0
		for product in self.reservationProductListFromPlace:
			x_pos=5
			ld=listTenDay[0]
			for d in listTenDay:
				if d == ld:
					m=first_month
					y=first_year
				elif d == ld+1:
					ld+=1
				else:
					m=last_month
					y=last_year
					ld=d
					
				# Evenement demi journér AM
				e=Event()
				e.date=str(d)+"/"+str(m)+"/"+str(y)
				e.hour=u"Matin"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+line+d-1))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position,e.y_position,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position, e.y_position,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				# Numero de la chambre
				e.objectTextID=self.reservationSC.create_text(e.x_position,e.y_position,text=product.number,fill="black",font=self.daysFT,anchor=NW)
				# Information sur le produit Infos Bulle
				balloonText=u"Famille de produit : "+product.productFamily.designation
				balloonText+=u"\nRéférence : "+product.reference.code
				balloonText+=u"\nDésignation : "+product.designation
				if product.description!=None and product.description!= "":balloonText+=u"\n---------------  Description \n"+product.description+u"\n---------------"
				if product.number!="0":balloonText+=u"\nNuméro : "+product.number
				balloonText+=u"\nNombre de couchage : "+str(product.sleeps)
				if product.area!=0:balloonText+=u"\nSurface : "+str(product.area)+u"m²"
				if product.floor!=0:balloonText+=u"\nEtage : "+str(product.floor)
				if product.tel!=None and product.tel!= "":balloonText+=u"\nTéléphone : "+product.tel
				if product.status=="S":balloonText+=u"\nEtat : Sale"
				elif product.status=="A":balloonText+=u"\nEtat : A vérifier"
				elif product.status=="P":balloonText+=u"\nEtat : Propre"
				elif product.status=="I":balloonText+=u"\nEtat : Intervention"
				elif product.status=="T":balloonText+=u"\nEtat : Traveaux"
				elif product.status=="M":balloonText+=u"\nEtat : Maintennance"
				else: balloonText+=u"\nEtat : Fermé"
				self.balloon.tagbind(self.reservationSC, e.objectTextID, balloonText)

				self.eventList.append(e)
				# Evenement demi journér PM
				e=Event()
				e.date=str(d)+"/"+str(m)+"/"+str(y)
				e.hour=u"Après-midi"
				e.x_position=x_pos
				e.y_position=y_pos
				e.productID=product.id
				e.tagID=u"TAG"+str(int(oddAndEven+oddAndEven+line+d-1))
				self.getLinkIDFromProductAtDate(e, product)
				e.objecPolygonID=self.reservationSC.create_polygon(e.x_position+e.size,e.y_position+e.size,
																									e.x_position, e.y_position+e.size,
																									e.x_position+e.size, e.y_position,
																									e.x_position+e.size, e.y_position+e.size,
																									tag=e.tagID,fill=e.color)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-1>", self.selectEvent)
				self.reservationSC.tag_bind (e.tagID, "<ButtonRelease-3>", self.makePopupReservation)
				# Reservation et interventions sur la chambre Infos Bulle
				balloonText=u""
				if e.date!=None:balloonText+=u"Date : "+e.date+u" - "+e.hour+u"\n"
				if e.stayVoucher!=None:balloonText+=u"N° de resa : "+e.stayVoucher+u"\n"
				if e.stayContact!=None:balloonText+=u"Contact : "+e.stayContact+u"\n"
				if e.stayContactTel!=None:balloonText+=u"Tél : "+e.stayContactTel+u"\n"
				if e.stayStatus!=None:balloonText+=e.stayStatus+u"\n"
				balloonText=balloonText.rstrip("\n")
				self.balloon.tagbind(self.reservationSC, e.objecPolygonID, balloonText)
				self.eventList.append(e) 
				x_pos+=60
				eventNum+=1
			y_pos+=60
			line+=10000
		self.reservationSC.resizescrollregion()

	def movetoXView(self, position=0.0):
		self.log.info("\txView position\t"+str(position))
		self.reservationSC.xview("moveto", position)

	def getLinkIDFromProductAtDate(self, event, product):
		date=event.date.split("/")
		d = datetime.date(int(date[2]), int(date[1]), int(date[0]))
		result=ProductChoice.select(ProductChoice.q.wish==product)
		for row in result:
			dateIn=datetime.date(int(row.stay.checkIn.strftime("%Y")),int(row.stay.checkIn.strftime("%m")),int(row.stay.checkIn.strftime("%d")))
			dateOut=datetime.date(int(row.stay.checkOut.strftime("%Y")),int(row.stay.checkOut.strftime("%m")),int(row.stay.checkOut.strftime("%d")))
			if dateIn<=d and dateOut>=d:
				if dateIn==d:
					if int(event.tagID[3])==2:
						event.stayID=row.stay.id
						event.stayVoucher=row.stay.voucher
						event.stayContact=row.stay.contact.fname+" "+row.stay.contact.lname
						event.stayContactTel=row.stay.contact.tel
						if row.stay.status=="R":
							event.color="#a7d6f7"
							event.stayStatus=u"Jour de d'arrivée (Séjour réservé)\nHeure d'arrivée : "+row.stay.checkIn.strftime("%H:%M")
						elif row.stay.status=="O":
							event.color="#f7eea7"
							event.stayStatus=u"Jour de d'arrivée (Séjour en option)\nHeure d'arrivée : "+row.stay.checkIn.strftime("%H:%M")
						elif row.stay.status=="F":
							event.color="#e6faab"
							event.stayStatus=u"Jour de d'arrivée (Séjour ferme)\nHeure d'arrivée : "+row.stay.checkIn.strftime("%H:%M")
						elif row.stay.status=="A":
							event.color="#fa7676"
							event.stayStatus=u"Séjour annulé"
						else:
							event.color="#f7eea7"
							event.stayStatus=u"Arrivée"
				elif dateOut==d:
					if int(event.tagID[3])==1:
						event.stayID=row.stay.id
						event.stayVoucher=row.stay.voucher
						event.stayContact=row.stay.contact.fname+" "+row.stay.contact.lname
						event.stayContactTel=row.stay.contact.tel
						if row.stay.status=="R":
							event.color="#d6a7f7"
							event.stayStatus=u"Jour de départ (Séjour réservé)\nHeure de départ : "+row.stay.checkOut.strftime("%H:%M")
						elif row.stay.status=="O":
							event.color="#f7c5a7"
							event.stayStatus=u"Jour de départ (Séjour en option)\nHeure de départ : "+row.stay.checkOut.strftime("%H:%M")
						elif row.stay.status=="F":
							event.color="#fad2ab"
							event.stayStatus=u"Jour de départ (Séjour ferme)\nHeure de départ : "+row.stay.checkOut.strftime("%H:%M")
						elif row.stay.status=="A":
							event.color="#fa7676"
							event.stayStatus=u"Séjour annulé"
						else:
							event.color="#f7c5a7"
							event.stayStatus=u"Départ"
				else:
					event.stayID=row.stay.id
					event.stayVoucher=row.stay.voucher
					event.stayContact=row.stay.contact.fname+" "+row.stay.contact.lname
					event.stayContactTel=row.stay.contact.tel
					if row.stay.status=="R":
						event.color="#a8a7f7"
						event.stayStatus=u"Séjour réservé"
					elif row.stay.status=="O":
						event.color="#f7daa7"
						event.stayStatus=u"Séjour en option"
					elif row.stay.status=="F":
						event.color="#faf5aa"
						event.stayStatus=u"Séjour ferme"
					elif row.stay.status=="A":
						event.color="#fa7676"
						event.stayStatus=u"Séjour annulé"
					else:
						event.color="#f7daa7"
						event.stayStatus=u"Séjour"
			# Check for ocupancyID
			ev_result=Ocupancy.select(AND(Ocupancy.q.product==product, Ocupancy.q.stay==row.stay))
			for ev_row in ev_result:
				event.ocupancyID=ev_row.id
			# TODO valider la comparaison des date object date et datetime
			#~ # Check for cleaningID
			#~ ev_result=Cleaning.select(AND(Cleaning.q.product==product, Cleaning.q.request==dateIn))
			#~ for ev_row in ev_result:
				#~ event.cleaningID=ev_row.id
			#~ # Check for technicalID
			#~ ev_result=Technical.select(AND(Technical.q.product==product, Technical.q.request==dateIn))
			#~ for ev_row in ev_result:
				#~ event.technicalID=ev_row.id

	def selectEvent(self, event):
		tag=self.reservationSC.gettags(CURRENT)
		obj=self.reservationSC.find_withtag(tag[0])
		for e in self.eventList:
			if str(e.tagID) == str(tag[0]):
				if e.color == "#bcfabf":e.color="grey80"
				else:e.color="#bcfabf"
				self.reservationSC.itemconfig(obj[0], fill=e.color)

	def selectReservationPlace(self, value):
		size=self.reservationPlaceCB.size()
		count=0
		while(count<size):
			if self.reservationPlaceCB.get(count) == value:
				self.getReservationProductListFromPlace(self.idListReservationPlace[count])
				break
			count+=1

	def selectMonth(self, value):
		size=self.monthCB.size()
		count=0
		while(count<size):
			if self.monthCB.get(count) == value:
				self.month_selected = count
				break
			count+=1

	def selectScreenMode(self, value):
		size=self.screenModeCB.size()
		count=0
		while(count<size):
			if self.screenModeCB.get(count) == value:
				self.screenMode = count
				if count == 0:
					self.reservationYearC.component('entryfield_entry').configure(state=NORMAL)
					self.monthCB.component('entryfield_entry').configure(state=DISABLED)
					self.monthCB.component('scrolledlist_listbox').configure(state=DISABLED)
					self.dateE.config(state=DISABLED)
					self.myCal1.config(state=DISABLED)
				elif count == 1:
					self.reservationYearC.component('entryfield_entry').configure(state=NORMAL)
					self.monthCB.component('entryfield_entry').configure(state=NORMAL)
					self.monthCB.component('scrolledlist_listbox').configure(state=NORMAL)
					self.dateE.config(state=DISABLED)
					self.myCal1.config(state=DISABLED)
				else:
					self.dateE.config(state=NORMAL)
					self.myCal1.config(state=NORMAL)
					self.reservationYearC.component('entryfield_entry').configure(state=DISABLED)
					self.monthCB.component('entryfield_entry').configure(state=DISABLED)
					self.monthCB.component('scrolledlist_listbox').configure(state=DISABLED)
				break
			count+=1

	def makePopupReservation(self,event):
		tag=self.reservationSC.gettags(CURRENT)
		for e in self.eventList:
			if str(e.tagID) == str(tag[0]):
				self.selectedEvent=e
		# create a menu
		popupResa = Menu(self, tearoff=0)
		popupResa.add_command(label=u"Ménage", command=self.popupActionCleaning)
		popupResa.add_command(label=u"Annulé le menu")
		# display the popup menu
		try:
			popupResa.tk_popup(event.x_root, event.y_root, 0)
		finally:
			# make sure to release the grab (Tk 8.0a1 only)
			popupResa.grab_release()

	def popupActionCleaning(self):
		cleanGui=CleaningGUI(balloon=self.balloon, log=self.log, path=self.path)
		if self.selectedEvent.cleaningID!=None:
			cleanGui.set(self.selectedEvent)
		else:
			cleanGui.setDateTime(self.selectedEvent)
			
	def ctrlCalendar(self,field):
		CalendarGUI(field=field, log=self.log, path=self.path)

	def getReservationProductListFromPlace(self, placeID):
		self.reservationProductListFromPlace = []
		result=Place.select(Place.q.id==placeID)
		for row in result:
			self.reservationPlaceSelected=row
		result=Product.select(Product.q.place==self.reservationPlaceSelected, orderBy=Product.q.number)
		for row in result:
			self.reservationProductListFromPlace.append(row)
		if self.screenMode == 0:
			thread.start_new_thread(self.drawReservationByYear, ())
		elif self.screenMode == 1:
			thread.start_new_thread(self.drawReservationByMonth, ())
		else:
			thread.start_new_thread(self.drawReservationByDay, ())
		#~ self.drawReservationByYear()

	# Methode utilisée a l'initialisation du module pour afficher les Résidences dans un comboBox
	def fillReservationPlace(self):
		self.reservationPlaceCB.delete(0,END)
		self.idListReservationPlace = []
		result=Place.select(orderBy=Place.q.company)
		for row in result:
			self.reservationPlaceCB.insert(END, row.company)
			self.idListReservationPlace.append(row.id)
			
	def fillScreenMode(self):
		self.screenMode=0
		self.screenModeCB.insert(END, u"par Année")
		self.screenModeCB.insert(END, u"par Mois")
		self.screenModeCB.insert(END, u"par Jours")
		
	def fillMonthCB(self):
		self.monthCB.insert(END, u"Janvier")
		self.monthCB.insert(END, u"Février")
		self.monthCB.insert(END, u"Mars")
		self.monthCB.insert(END, u"Avril")
		self.monthCB.insert(END, u"Mai")
		self.monthCB.insert(END, u"Juin")
		self.monthCB.insert(END, u"Juillet")
		self.monthCB.insert(END, u"Aôut")
		self.monthCB.insert(END, u"Septembre")
		self.monthCB.insert(END, u"Octobre")
		self.monthCB.insert(END, u"Novembre")
		self.monthCB.insert(END, u"Décembre")
	# FIN planning des menages  *******************************************************************************